<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>电梯导航</title>
  <style>
    *{
      padding: 0;
      margin: 0;
    }

    .content{
      width:90%;
      margin: 0 auto;
    }
    .content  div{
      margin-bottom: 20px ;
    }
    .elevator{
      position: fixed;
      top: 100px;
      right: 110px;
      background-color: darkgray;
    }
    .elevator ul{
      list-style-type: none;

      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
    }
    .elevator li{
      width: 40px;
      height: 40px;
      line-height: 40px;
      font-size: 20px;
      padding-left: 20px;
    }
    .active{
      color: #db0000;
      background-color: aqua;
    }
  </style>
</head>
<body>

<div class="content">
  <div style="height: 500px;width: 90%; background-color: antiquewhite;">第一块</div>
  <div style="height: 500px;width: 90%; background-color: aquamarine;">第二块</div>
  <div style="height: 500px;width: 90%; background-color: cadetblue;">第三块</div>
  <div style="height: 1000px;width: 90%; background-color:gainsboro;">第四块</div>
</div>
<div class="elevator">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>
<script>
  // 获得导航需要的楼层
  const floor=document.querySelectorAll('.content div')
  // 获取电梯导航栏中所有的li,可以理解为楼层按钮
  const navBar=document.querySelectorAll('.elevator li')
  // 获得导航栏盒子
  const elevator=document.querySelector('.elevator')
  // 定义一个数组储存楼层高度
  let floorHeight = []

  // 点击相应的楼层按钮，跳转到相应的楼层
  for(let i=0;i< floor.length;i++){
    //  获得每个楼层据顶部的高度
    floorHeight[i]=floor[i].offsetTop
    // 给每个楼层添加点击事件
    navBar[i].addEventListener('click',function(){
      // 切换active事件,楼层按钮高亮显示
      let active=document.querySelector('.elevator .active')
      if(active)  active.classList.remove('active')
      this.classList.add('active')
      // 页面滚动到相应的楼层
      document.documentElement.scrollTop=floorHeight[i]
    })
  }


  // 页面滚动到相应的位置，进行高亮显示
  window.addEventListener('scroll',function(){
    const n=document.documentElement.scrollTop
    for(let i=0;i< navBar.length;i++){
      console.log(i);
      if((n> floorHeight[i]&&n<floorHeight[i+1])||(i===navBar.length-1&&n>floorHeight[i])){
        let active=document.querySelector('.elevator .active')
        if(active)  active.classList.remove('active')
        navBar[i].classList.add('active')
      }
    }
  })
</script>

</body>
</html>
